package com.yxuan.springboot.component;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yxuan.springboot.CustomizedException.DefaultException;
import com.yxuan.springboot.controller.DouyinPayController;
import com.yxuan.springboot.model.ThirdToken;
import com.yxuan.springboot.model.UserVip;
import com.yxuan.springboot.service.ThirdTokenService;
import com.yxuan.springboot.service.UserVipService;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


import javax.annotation.Resource;
import java.util.*;


/**
 * 计时器
 */
@Component
public class Timer {

    @Autowired
    private UserVipService userVipService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ThirdTokenService thirdTokenService;


    @Resource(name = "wxPayClient")
    private CloseableHttpClient dyPayClient;

    @Value("${weixin.appid}")
    private String APP_ID;
    @Value("${weixin.appsecret}")
    private String APP_SECRET;
    @Value("${douyin.appid}")
    private String DY_APP_ID;
    @Value("${douyin.appsecret}")
    private String DY_APP_SECRET;

    /**
     * 判断会员是否到期，到期则将vip值设为非会员的值
     */
    @Scheduled(cron = "1 0 0 * * ?")
    public void refreshVipFreeCnt() throws Exception {

        List<UserVip> allOneVips = userVipService.findAllVips();


        //遍历会员集合，比较当前日期与会员到期日期，若过期则将vip级别设为0,其他字段值设为0
        for (int i = 0; i < allOneVips.size(); i++) {
            UserVip vip = allOneVips.get(i);
            UserVip newVip = new UserVip();
            newVip.setUserId(vip.getUserId());

            //比较当前日期与会员到期日期

/*          如果当前日期在参数日期之前，则返回一个负数；
            如果当前日期和参数日期相等，则返回0；
            如果当前日期在参数日期之后，则返回一个正数。*/

            Date nowaDay = new Date();
            if(vip.getExpirationTime()==null){
                vip.setVipRank("0");
            }else {
                //过期的处理
                if (nowaDay.compareTo(vip.getExpirationTime()) >= 0) {

                    newVip.setVipRank("0");
                    newVip.setFillingTimes("0");
                    newVip.setProbabilityTimes("1");
                    newVip.setCourseSelectionTimes("0");
                    newVip.setInfoUpdTimes("1");
                    newVip.setGptTimes("3");

                }
            }
            userVipService.upd(newVip);

        }


    }


    /**
     * 重置每个等级会员用户的修改个人信息次数
     *
     * @throws Exception
     */
    @Scheduled(cron = " 1 0 0 * * ?")
    public void resetVipUpdInfoNum() throws Exception {

        //将所有会员每天的测录取率次数重置为50
        List<UserVip> allOneVips = userVipService.findAllVips();
        for (int i = 0; i < allOneVips.size(); i++) {
            UserVip userVip = allOneVips.get(i);
            UserVip userVip1 = new UserVip();
            userVip1.setUserId(userVip.getUserId());
            userVip1.setProbabilityTimes("50");
            userVipService.upd(userVip1);
        }

        //将所有非会员的测录取率次数重置为1
        List<UserVip> allPoors = userVipService.findAllPoors();
        for (int i = 0; i < allPoors.size(); i++) {
            UserVip userVip = new UserVip();
            userVip.setUserId(allPoors.get(i).getUserId());
            userVip.setProbabilityTimes("1");
            userVipService.upd(userVip);
        }



        //查询每个等级的所有用户，遍历集合，对每个用户进行修改

        for (int i = 0; i <= 3; i++) {

            String rank = String.valueOf(i);
            //查询到rank等级下的所有用户
            List<UserVip> vipsByCondition = userVipService.findVipsByCondition(rank);
            for (int j = 0; j < vipsByCondition.size(); j++) {

                UserVip targetVip = vipsByCondition.get(j);
                Integer integer = userVipService.updVipUpdInfoNum(targetVip.getUserId(), i);

            }
        }

    }





    @Scheduled(cron = "0 0 */1 * * ?")      // 1h  间隔一小时定时执行
//    @Scheduled(cron = "*/10 * * * * ?")         // 10s
    public void AutoReloadToken() throws Exception {
        // 获取token Url   小程序token
        String CodeToOpenId = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        // 公众号token
        //String CodeToOpenId2 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ AppData.getG_appid() +"&secret="+ AppData.getG_secret();
        // String 接受参数  获取小程序token
        String result = restTemplate.getForObject(CodeToOpenId, String.class);
        // 获取公众号token
        //    String result2 = restTemplate.getForObject(CodeToOpenId2, String.class);
        // 获取结果转 json
        JSONObject jsonObject = JSON.parseObject(result);
        // json中获取 id
        String access_token = (String) jsonObject.get("access_token");
        ThirdToken firm = new ThirdToken();
        firm.setAccessToken(access_token);
//            firm.setId(1L);
//            firm.setCreated(now2);
        firm.setTokenType("小程序token");
        thirdTokenService.upd(firm);
    }



    @Scheduled(cron = "0 0 */1 * * ?")      // 1h  间隔一小时定时执行
//    @Scheduled(cron = "*/10 * * * * ?")         // 10s
    public void AutoReloadDouYinToken() throws Exception {



        Map<String, Object> parame = new LinkedHashMap<>();
        //抖音小程序app
        parame.put("appid", DY_APP_ID);
        // 商户订单编号
        parame.put("secret", DY_APP_SECRET);

        parame.put("grant_type", "client_credential");        //小程序用户的 open_id，通过 code2Session 获取


        try {
            Map<String,Object> getpost = DouyinPayController.getDDpost(parame, dyPayClient);
            String accessToken = (String) ((Map<String, Object>)getpost.get("data")).get("access_token");
            ThirdToken firm = new ThirdToken();
            firm.setAccessToken(accessToken);
            firm.setTokenType("抖音小程序token");
            thirdTokenService.upd(firm);


        } catch (DefaultException e) {
            e.printStackTrace();
        }





    }

}
